package com.mjfeed.controller.admin;

import java.util.Collections;
import java.util.Date;
import java.util.Iterator;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.mjfeed.FileInfo.FileType;
import com.mjfeed.controller.BaseController;
import com.mjfeed.entity.Product;
import com.mjfeed.entity.ProductCategory;
import com.mjfeed.entity.ProductImage;
import com.mjfeed.service.FileService;
import com.mjfeed.service.ProductCategoryService;
import com.mjfeed.service.ProductImageService;
import com.mjfeed.service.ProductService;
import com.mjfeed.util.Pagination;
import com.mjfeed.util.ParamBean;
import com.mjfeed.util.Format;

/**
 * @description 商品
 * @author zhaominglei
 * @date 2014年10月1日
 */
@Controller("adminProductController")
@RequestMapping("/admin/product")
public class ProductController extends BaseController {
	@Resource(name="productService")
	private ProductService productService;
	@Resource(name="productImageService")
	private ProductImageService productImageService;
	@Resource(name="productCategoryService")
	private ProductCategoryService productCategoryService;
	@Resource(name="fileService")
	private FileService fileService;
	
	@RequestMapping(value = "/list" ,method=RequestMethod.GET)
	public String list(ParamBean paramBean, HttpServletRequest request, HttpServletResponse response, Model model){
		paramBean.setUrl(getBasePath(request) + "admin/product/list.shtml");
		int p = (Format.null2Zero(request.getParameter("p")) == 0) ? 1 : Format.null2Zero(request.getParameter("p"));
		paramBean.setPage(p);
		Pagination<Product> pagination = productService.getPagination(paramBean);
		request.setAttribute("pagination", pagination);
		return "admin/product/list";
	}
	
	@RequestMapping(value = "/add" ,method=RequestMethod.GET)
	public String add(HttpServletRequest request, HttpServletResponse response, Model model){
		request.setAttribute("productCategoryTree", productCategoryService.findTree());
		return "admin/product/add";
	}
	
	@RequestMapping(value = "/save" ,method=RequestMethod.POST)
	public String save(Product product, HttpServletRequest request, HttpServletResponse response, Model model){
		for (Iterator<ProductImage> iterator = product.getProductImages().iterator(); iterator.hasNext();) {
			ProductImage productImage = iterator.next();
			if (productImage == null || productImage.isEmpty()) {
				iterator.remove();
				continue;
			}
			if (productImage.getFile() != null && !productImage.getFile().isEmpty()) {
				if (!fileService.isValid(FileType.image, productImage.getFile())) {
					return "redirect:add.shtml";
				}
			}
		}
		String productCategoryId = request.getParameter("productCategoryId");
		if (productCategoryId == null || productCategoryId.equals("")) {
			return ERROR_VIEW;
		}
		ProductCategory productCategory = productCategoryService.getById(ProductCategory.class, Long.valueOf(productCategoryId));
		if (productCategory == null) {
			return ERROR_VIEW;
		}
		product.setProductCategory(productCategory);
		product.setFullName("");
		product.setAllocatedStock(0);
		product.setScore(0F);
		product.setTotalScore(0L);
		product.setScoreCount(0L);
		product.setHits(0L);
		product.setWeekHits(0L);
		product.setMonthHits(0L);
		product.setSales(0L);
		product.setWeekSales(0L);
		product.setMonthSales(0L);
		product.setWeekHitsDate(new Date());
		product.setMonthHitsDate(new Date());
		product.setWeekSalesDate(new Date());
		product.setMonthSalesDate(new Date());
		product.setIsMarketable(true);
		product.setIsList(true);
		product.setIsGift(false);
		product.setIsTop(false);
		product.setPoint(0L);
		
		for (ProductImage productImage : product.getProductImages()) {
			productImageService.build(productImage);
		}
		Collections.sort(product.getProductImages());
		if (product.getImage() == null && product.getThumbnail() != null) {
			product.setImage(product.getThumbnail());
		}
		productService.save(product);
		return "redirect:/admin/product/list.shtml";
	}
	
	@RequestMapping(value = "/edit" ,method=RequestMethod.GET)
	public String edit(Long id, HttpServletRequest request, HttpServletResponse response, Model model){
		request.setAttribute("productCategoryTree", productCategoryService.findTree());
		request.setAttribute("product", productService.getById(Product.class, id));
		return "admin/product/edit";
	}
	
	@RequestMapping(value = "/update" ,method=RequestMethod.POST)
	public String update(Product product, HttpServletRequest request, HttpServletResponse response, Model model){
		for (Iterator<ProductImage> iterator = product.getProductImages().iterator(); iterator.hasNext();) {
			ProductImage productImage = iterator.next();
			if (productImage == null || productImage.isEmpty()) {
				iterator.remove();
				continue;
			}
			if (productImage.getFile() != null && !productImage.getFile().isEmpty()) {
				if (!fileService.isValid(FileType.image, productImage.getFile())) {
					return "redirect:edit.shtml?id="+product.getId();
				}
			}
		}
		
		Product pProduct = productService.getById(Product.class, product.getId());
		if (pProduct == null) {
			return ERROR_VIEW;
		}
		if (StringUtils.isNotEmpty(product.getSn()) && !productService.snUnique(pProduct.getSn(), product.getSn())) {
			return ERROR_VIEW;
		}
		String productCategoryId = request.getParameter("productCategoryId");
		if (productCategoryId == null || productCategoryId.equals("")) {
			return ERROR_VIEW;
		}
		ProductCategory productCategory = productCategoryService.getById(ProductCategory.class, Long.valueOf(productCategoryId));
		if (productCategory == null) {
			return ERROR_VIEW;
		}
		product.setProductCategory(productCategory);
		product.setFullName("");
		product.setAllocatedStock(0);
		product.setScore(0F);
		product.setTotalScore(0L);
		product.setScoreCount(0L);
		product.setHits(0L);
		product.setWeekHits(0L);
		product.setMonthHits(0L);
		product.setSales(0L);
		product.setWeekSales(0L);
		product.setMonthSales(0L);
		product.setWeekHitsDate(new Date());
		product.setMonthHitsDate(new Date());
		product.setWeekSalesDate(new Date());
		product.setMonthSalesDate(new Date());
		product.setIsMarketable(true);
		product.setIsList(true);
		product.setIsGift(false);
		product.setIsTop(false);
		product.setPoint(0L);
		
		if (product.getProductImages() != null && product.getProductImages().size() > 0) {
			for (ProductImage productImage : product.getProductImages()) {
				productImageService.build(productImage);
			}
		} else {
			product.setProductImages(pProduct.getProductImages());
		}
		
		Collections.sort(product.getProductImages());
		if (product.getImage() == null && product.getThumbnail() != null) {
			product.setImage(product.getThumbnail());
		}
		productService.update(product);
		return "redirect:/admin/product/list.shtml";
	}
	
	@RequestMapping(value = "/view" ,method=RequestMethod.GET)
	public String view(Long id, HttpServletRequest request, HttpServletResponse response, Model model){
		request.setAttribute("product", productService.getById(Product.class, id));
		return "admin/product/view";
	}
}
